package asia.doing.service.common;

import asia.doing.common.enums.RoleEnum;
import asia.doing.common.utils.TokenUtils;
import asia.doing.common.utils.UUIDUtils;
import asia.doing.entity.Account;
import asia.doing.entity.Comment;
import asia.doing.mapper.CommentMapper;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service(value = "commonCommentService")
public class CommonCommentService {
    @Resource
    private CommentMapper commentMapper;

    public void add(Comment comment){
        Account currentUser = TokenUtils.getCurrentUser();
        if(RoleEnum.USER.name().equals(currentUser.getName())){
            comment.setUserId(currentUser.getId());
        }
        comment.setTime(DateUtil.now());
        // 使用uuid作为唯一性的id进行插入数据
        comment.setId(UUIDUtils.getUUIDInOrderId());
        commentMapper.insert(comment);
        //如果这条评论是根评论，那么则将rootId设置为id一样
        if(comment.getRootId() == null){
            comment.setRootId(comment.getId());
            commentMapper.updateById(comment);
        }
    }

    public void deleteById(Long id){
        commentMapper.deleteById(id);
    }

    public void deleteBatch(List<Long> ids){
        for (Long id : ids) {
            commentMapper.deleteById(id);
        }
    }

    public void updateById(Comment comment){
        commentMapper.updateById(comment);
    }

    public Comment selectById(Long id){
        return commentMapper.selectById(id);
    }

    public List<Comment> selectAll(Comment comment){
        return commentMapper.selectAll(comment);
    }

    public Long selectCount(Long fid, String module){
        return commentMapper.selectCount(fid, module);
    }

    public PageInfo<Comment> selectPage(Comment comment, Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize);
        List<Comment> list = commentMapper.selectAll(comment);
        return PageInfo.of(list);
    }


    public List<Comment> selectForUser(Comment comment){
        List<Comment> commentList = commentMapper.selectAll(comment);
        for (Comment c : commentList) {
            Comment param = new Comment();
            param.setRootId(c.getId());
            List<Comment> children = this.selectAll(param);
            children = children.stream().filter(child -> !child.getId().equals(c.getId())).collect(Collectors.toList());
            c.setChildren(children);
        }
        return commentList;
    }
}
